﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IntegrationTest
{
    public class TestFactory
    {
        public TestFactory(string config)
        {
            mSection = (TestSection)System.Configuration.ConfigurationManager.GetSection(config);
            foreach (TestCaseConf item in mSection.Cases)
            {
                TestCase tc = new TestCase(item);
                tc.TestCompleted = OnTestCompleted;
                Cases.Add(tc);
            }
            System.Threading.ThreadPool.SetMinThreads(mSection.Threads, mSection.IOThreads);
        }

        private TestSection mSection;

        private int mCompleteds = 0;

        private void OnTestCompleted(TestCase value)
        {
            System.Threading.Interlocked.Increment(ref mCompleteds);

        }


        public bool Completed
        {
            get
            {
                return mCompleteds == mCases.Count;
            }
        }

        private List<TestCase> mCases = new List<TestCase>();

        public IList<TestCase> Cases
        {
            get
            {
                return mCases;
            }
        }

        public void Run()
        {
            mCompleteds = 0;
           
            foreach (TestCase tc in Cases)
            {
                tc.Test();
            }
            System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(o => {
                while (true)
                {
                    int count = 0;
                    foreach (TestCase tc in Cases)
                    {
                        if (!tc.Second())
                            count++;
                    }
                    if (count == Cases.Count)
                        break;
                    System.Threading.Thread.Sleep(990);
                }
            }), null);

        }
    }
}
